package com.tencent.qcloud.timchat.utils;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMElem;
import com.tencent.imsdk.TIMElemType;
import com.tencent.imsdk.TIMFaceElem;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMMessage;
import com.tencent.imsdk.TIMMessageStatus;
import com.tencent.imsdk.TIMTextElem;
import com.tencent.imsdk.TIMUserProfile;
import com.tencent.imsdk.TIMValueCallBack;
import com.tencent.imsdk.ext.message.TIMMessageDraft;
import com.tencent.imsdk.ext.message.TIMMessageExt;
import com.tencent.imsdk.ext.message.TIMMessageLocator;
import com.wbao.dianniu.R;
import com.wbao.dianniu.db.TencentUserBean;
import com.wbao.dianniu.db.TencentUserHelper;
import com.wbao.dianniu.update.ImChangerManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.FileUtil;
import com.wbao.dianniu.utils.Notification;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ChatActivity extends FragmentActivity implements ChatView {

    private static final String TAG = "ChatActivity";

    private List<Message> messageList = new ArrayList<>();
    private ChatAdapter adapter;
    private ListView listView;
    private ChatPresenter presenter;
    private ChatInput input;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int IMAGE_STORE = 200;
    private static final int FILE_CODE = 300;
    private static final int IMAGE_PREVIEW = 400;
    private static final int VIDEO_RECORD = 500;
    private Uri fileUri;
    private VoiceSendingView voiceSendingView;
    private String identify;
    private RecorderUtil recorder = new RecorderUtil();
    private TIMConversationType type;
    private String titleStr;
    // 对方头像
    private String toUrl;
    // 自己头像
    private String selfUrl;
    private Handler handler = new Handler();
    private TemplateTitle title;
    private boolean needReflashTitle, needReflashUrl;

    public static void navToChat(Context context, String identify, TIMConversationType type, String toUrl, String name, String selfUrl) {
        Intent intent = new Intent(context, ChatActivity.class);
        intent.putExtra("identify", identify);
        intent.putExtra("type", type);
        intent.putExtra("peer_url", toUrl);
        intent.putExtra("self_url", selfUrl);
        intent.putExtra("name", name);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_chat);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        identify = getIntent().getStringExtra("identify");
        type = (TIMConversationType) getIntent().getSerializableExtra("type");
        toUrl = getIntent().getStringExtra("peer_url");
        selfUrl = getIntent().getStringExtra("self_url");
        titleStr = getIntent().getStringExtra("name");
        presenter = new ChatPresenter(this, identify, type);
        input = (ChatInput) findViewById(R.id.input_panel);
        input.setChatView(this);
        adapter = new ChatAdapter(this, R.layout.item_message, messageList, selfUrl, toUrl, identify);
        listView = (ListView) findViewById(R.id.list);
        listView.setAdapter(adapter);
        listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL);
        listView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        input.setInputMode(ChatInput.InputMode.NONE);
                        break;
                }
                return false;
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {

            private int firstItem;

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && firstItem == 0) {
                    //如果拉到顶端读取更多消息
                    presenter.getMessage(messageList.size() > 0 ? messageList.get(0).getMessage() : null);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                firstItem = firstVisibleItem;
            }
        });
        registerForContextMenu(listView);
        title = (TemplateTitle) findViewById(R.id.chat_title);
        switch (type) {
            case C2C:
                if (FriendshipInfo.getInstance().isFriend(identify)) {
                    FriendProfile profile = FriendshipInfo.getInstance().getProfile(identify);
                    if (profile != null) {
                        titleStr = profile.getName();
                    }
                } else {
                }
                if (titleStr.equals(identify)) {
                    titleStr = titleStr.replace("qa", "").replace("prod", "");
                }
                title.setTitleText(titleStr);
                break;
            /*case Group:
                title.setMoreImg(R.drawable.btn_group);
                title.setMoreImgAction(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ChatActivity.this, GroupProfileActivity.class);
                        intent.putExtra("identify", identify);
                        startActivity(intent);
                    }
                });
                title.setTitleText(GroupInfo.getInstance().getGroupName(identify));
                break;*/

        }
        voiceSendingView = (VoiceSendingView) findViewById(R.id.voice_sending);
        presenter.start();

        // 每次进入聊天页面，更新头像数据
        List<String> users = new ArrayList<>();
        users.add(identify);
        reqUserInfo(users);
    }

    /*private void AsyncInitTask() {
        new AsyncTask() {
            @Override
            protected Object doInBackground(Object[] params) {
                final List<String> permissionsList = new ArrayList<>();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if ((checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED))
                        permissionsList.add(Manifest.permission.READ_PHONE_STATE);
                    if ((checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED))
                        permissionsList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    if (permissionsList.size() == 0) {
                        init();
                    } else {
                        requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                REQUEST_PERMISSION);
                    }
                } else {
                    init();
                }
                return null;
            }
        }.execute();
    }*/


    /**
     * 进入聊天页面时，请求用户头像和昵称数据-- 更新操作
     */
    private void reqUserInfo(List<String> users) {

        // 请求头像数据
        TIMFriendshipManager.getInstance().getUsersProfile(users, new TIMValueCallBack<List<TIMUserProfile>>() {
            @Override
            public void onError(int i, String s) {
                Log.e(TAG, "getUsersProfile failed: " + i + " desc:" + s);
            }

            @Override
            public void onSuccess(List<TIMUserProfile> timUserProfiles) {
                if (null != timUserProfiles && timUserProfiles.size() > 0) {
                    // 更新到缓存...
                    for (int i = 0; i < timUserProfiles.size(); i++) {
//                        Log.e(TAG, i + " 收到头像数据 并更新... " + timUserProfiles.get(i).getNickName());
                        TencentUserBean bean = new TencentUserBean();
                        bean.setIdentify(timUserProfiles.get(i).getIdentifier());
                        bean.setNiceName(timUserProfiles.get(i).getNickName());
                        bean.setFaceUrl(timUserProfiles.get(i).getFaceUrl());
                        TencentUserHelper.insertTencentUser(bean);
                    }
                    updateUserInfo(timUserProfiles);
                }
            }
        });
    }

    /**
     * 更新页面数据
     *
     * @param timUserProfiles
     */
    private void updateUserInfo(List<TIMUserProfile> timUserProfiles) {
        for (TIMUserProfile res : timUserProfiles) {
            if (res.getIdentifier().equals(identify)) {
                if (!TextUtils.isEmpty(res.getNickName())) {
                    if (!titleStr.equals(res.getNickName())) {
//                        Log.e(TAG,"需要更新niceName。。。。");
                        needReflashTitle = true;
                        titleStr = res.getNickName();
                    }
                }
                if (!TextUtils.isEmpty(res.getFaceUrl())) {
                    if (!TextUtils.isEmpty(toUrl)) {
                        if (!toUrl.equals(res.getFaceUrl())) {
//                            Log.e(TAG,"需要更新url。。。。");
                            needReflashUrl = true;
                            toUrl = res.getFaceUrl();
                        }
                    } else {
//                        Log.e(TAG,"需要更新url。。。。");
                        needReflashUrl = true;
                        toUrl = res.getFaceUrl();
                    }


                } else {
                    if (!TextUtils.isEmpty(toUrl)) {
//                        Log.e(TAG,"需要更新url。。。。");
                        needReflashUrl = true;
                        toUrl = res.getFaceUrl();
                    }
                }

                break;
            }
        }
        if (needReflashTitle) {
            if (titleStr.equals(identify)) {
                titleStr = titleStr.replace("qa", "").replace("prod", "");
            }
            title.setTitleText(titleStr);
        }
        if (needReflashUrl) {
            adapter.updateToUrl(toUrl);
            adapter.notifyDataSetChanged();
        }

        //  通知更新～～～
        if (needReflashTitle || needReflashUrl) {
//            Log.e(TAG,"通知更新用户头像数据。。。。");
            ImChangerManager.getInstance().imUserInfoChange(identify, titleStr, toUrl);
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //退出聊天界面时输入框有内容，保存草稿
        if (input.getText().length() > 0) {
            TextMessage message = new TextMessage(input.getText());
            presenter.saveDraft(message.getMessage());
        } else {
            presenter.saveDraft(null);
        }
//        RefreshEvent.getInstance().onRefresh();
        presenter.readMessages();
        MediaUtil.getInstance().stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.stop();
        if (null != input) {
            input.removeEditText();
        }
    }


    /**
     * 显示消息
     *
     * @param message
     */
    @Override
    public void showMessage(TIMMessage message) {
//        Log.e(TAG,"showMessage one");
        if (message == null) {
            adapter.notifyDataSetChanged();
        } else {
            Message mMessage = MessageFactory.getMessage(message);
            if (mMessage != null) {
                if (mMessage instanceof CustomMessage) {
                    CustomMessage.Type messageType = ((CustomMessage) mMessage).getType();
                    switch (messageType) {
                        case TYPING:
                            title.setTitleText(getString(R.string.chat_typing));
                            handler.removeCallbacks(resetTitle);
                            handler.postDelayed(resetTitle, 3000);
                            break;
                        default:
                            break;
                    }
                } else {
                    if (messageList.size() == 0) {
                        mMessage.setHasTime(null);
                    } else {
                        mMessage.setHasTime(messageList.get(messageList.size() - 1).getMessage());
                    }
                    messageList.add(mMessage);
                    adapter.notifyDataSetChanged();
                    listView.setSelection(adapter.getCount() - 1);
                }

            }
        }

    }

    /**
     * 显示消息
     *
     * @param messages
     */
    @Override
    public void showMessage(List<TIMMessage> messages) {
//        Log.e(TAG,"showMessage list ");
        title.dismissProgress();
        int newMsgNum = 0;
        for (int i = 0; i < messages.size(); ++i) {
            Message mMessage = MessageFactory.getMessage(messages.get(i));
            if (mMessage == null || messages.get(i).status() == TIMMessageStatus.HasDeleted)
                continue;
            if (mMessage instanceof CustomMessage && (((CustomMessage) mMessage).getType() == CustomMessage.Type.TYPING ||
                    ((CustomMessage) mMessage).getType() == CustomMessage.Type.INVALID)) continue;
            ++newMsgNum;
            if (i != messages.size() - 1) {
                mMessage.setHasTime(messages.get(i + 1));
                messageList.add(0, mMessage);
            } else {
                mMessage.setHasTime(null);
                messageList.add(0, mMessage);
            }
        }
        adapter.notifyDataSetChanged();
        listView.setSelection(newMsgNum);
    }

    @Override
    public void showRevokeMessage(TIMMessageLocator timMessageLocator) {
//        Log.e(TAG,"showRevokeMessage  ");
        for (Message msg : messageList) {
            TIMMessageExt ext = new TIMMessageExt(msg.getMessage());
            if (ext.checkEquals(timMessageLocator)) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 清除所有消息，等待刷新
     */
    @Override
    public void clearAllMessage() {
        messageList.clear();
    }

    /**
     * 发送消息成功
     *
     * @param message 返回的消息
     */
    @Override
    public void onSendMessageSuccess(TIMMessage message) {
        showMessage(message);
    }

    /**
     * 发送消息失败
     *
     * @param code 返回码
     * @param desc 返回描述
     */
    @Override
    public void onSendMessageFail(int code, String desc, TIMMessage message) {
        long id = message.getMsgUniqueId();
        for (Message msg : messageList) {
            if (msg.getMessage().getMsgUniqueId() == id) {
                switch (code) {
                    case 80001:
                        //发送内容包含敏感词
                        msg.setDesc(getString(R.string.chat_content_bad));
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        }

        adapter.notifyDataSetChanged();

    }

    /**
     * 发送图片消息
     */
    @Override
    public void sendImage() {
        Intent intent_album = new Intent("android.intent.action.GET_CONTENT");
        intent_album.setType("image/*");
        startActivityForResult(intent_album, IMAGE_STORE);
    }

    /**
     * 发送照片消息
     */
    @Override
    public void sendPhoto() {
        Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent_photo.resolveActivity(getPackageManager()) != null) {
            File tempFile = FileUtil.getTempFile(FileUtil.FileType.IMG);
            if (tempFile != null) {
                fileUri = Uri.fromFile(tempFile);
            }
            intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(intent_photo, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    }

    /**
     * 发送文本消息
     */
    @Override
    public void sendText() {
        Message message = new TextMessage(input.getText());
        presenter.sendMessage(message.getMessage());
        input.setText("");
    }

    /**
     * 发送文件
     */
    @Override
    public void sendFile() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        startActivityForResult(intent, FILE_CODE);
    }


    /**
     * 开始发送语音消息
     */
    @Override
    public void startSendVoice() {
        voiceSendingView.setVisibility(View.VISIBLE);
        voiceSendingView.showRecording();
        recorder.startRecording();

    }

    /**
     * 结束发送语音消息
     */
    @Override
    public void endSendVoice() {
        voiceSendingView.release();
        voiceSendingView.setVisibility(View.GONE);
        recorder.stopRecording();
        if (recorder.getTimeInterval() < 1) {
            Notification.toast(this, getResources().getString(R.string.chat_audio_too_short));
        } else if (recorder.getTimeInterval() > 60) {
            Notification.toast(this, getResources().getString(R.string.chat_audio_too_long));
        } else {
            Message message = new VoiceMessage(recorder.getTimeInterval(), recorder.getFilePath());
            presenter.sendMessage(message.getMessage());
        }
    }

    /**
     * 发送小视频消息
     *
     * @param fileName 文件名
     */
    @Override
    public void sendVideo(String fileName) {
        Message message = new VideoMessage(fileName);
        presenter.sendMessage(message.getMessage());
    }


    /**
     * 结束发送语音消息
     */
    @Override
    public void cancelSendVoice() {
        voiceSendingView.release();
        voiceSendingView.setVisibility(View.GONE);
        recorder.stopRecording();
        /*if (recorder.getTimeInterval() < 1) {
            Toast.makeText(this, getResources().getString(R.string.chat_audio_too_short), Toast.LENGTH_SHORT).show();
        } else if (recorder.getTimeInterval() > 60) {
            Toast.makeText(this, getResources().getString(R.string.chat_audio_too_long), Toast.LENGTH_SHORT).show();
        } else {
            Message message = new VoiceMessage(recorder.getTimeInterval(), recorder.getFilePath());
            presenter.sendMessage(message.getMessage());
        }*/
    }

    /**
     * 刷新取消发送声音页面
     */
    @Override
    public void cancelRefreshVoice() {
        voiceSendingView.unpressVoice();
    }

    /**
     * 恢复发送声音页面
     */
    @Override
    public void recoverySendVoice() {
        voiceSendingView.recoveryVoice();
    }

    /**
     * 正在发送
     */
    @Override
    public void sending() {
        if (type == TIMConversationType.C2C) {
            Message message = new CustomMessage(CustomMessage.Type.TYPING);
            presenter.sendOnlineMessage(message.getMessage());
        }
    }

    /**
     * 显示草稿
     */
    @Override
    public void showDraft(TIMMessageDraft draft) {
        input.getText().append(TextMessage.getString(draft.getElems(), this));
    }

    @Override
    public void videoAction() {
       /* Intent intent = new Intent(this, TCVideoRecordActivity.class);
        startActivityForResult(intent, VIDEO_RECORD);*/
    }

    @Override
    public void showToast(String msg) {
        Notification.toast(this, msg);
    }


    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
        Message message = messageList.get(info.position);
        menu.add(0, 1, Menu.NONE, getString(R.string.chat_del));
        if (message.isSendFail()) {
            menu.add(0, 2, Menu.NONE, getString(R.string.chat_resend));
        } else if (message.getMessage().isSelf()) {
            menu.add(0, 4, Menu.NONE, getString(R.string.chat_pullback));
        }
        if (message instanceof ImageMessage || message instanceof FileMessage) {
            menu.add(0, 3, Menu.NONE, getString(R.string.chat_save));
        }
        if (message instanceof TextMessage) {
            menu.add(0, 5, Menu.NONE, "复制");
        }
    }


    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Message message = messageList.get(info.position);
        switch (item.getItemId()) {
            case 1:
                message.remove();
                messageList.remove(info.position);
                adapter.notifyDataSetChanged();
                break;
            case 2:
                messageList.remove(message);
                presenter.sendMessage(message.getMessage());
                break;
            case 3:
                message.save();
                break;
            case 4:
                presenter.revokeMessage(message.getMessage());
                break;
            case 5:
                TIMMessage timMessage = message.getMessage();
                boolean hasText = false;
                if (timMessage.getElementCount() > 0) {
                    TIMElem elems = timMessage.getElement(0);
                    if (elems.getType() == TIMElemType.Text) {
                        hasText = true;
                    }
                    SpannableStringBuilder stringBuilder = getString(elems, this);
                    if (!hasText) {
                        stringBuilder.insert(0, " ");
                    }
                    ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                    cmb.setText(stringBuilder.toString());
                    Notification.showToastMsg(this, "内容已复制");
                } else {
                    Notification.showToastMsg(this, "内容为空");
                }
                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }


    public static SpannableStringBuilder getString(TIMElem elems, Context context) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
        switch (elems.getType()) {
            case Face:
                TIMFaceElem faceElem = (TIMFaceElem) elems;
                int startIndex = stringBuilder.length();
                try {
                    AssetManager am = context.getAssets();
                    InputStream is = am.open(String.format("emoticon/%d.gif", faceElem.getIndex()));
                    if (is == null) break;
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    Matrix matrix = new Matrix();
                    int width = bitmap.getWidth();
                    int height = bitmap.getHeight();
                    matrix.postScale(2, 2);
                    Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
                            width, height, matrix, true);
                    ImageSpan span = new ImageSpan(context, resizedBitmap, ImageSpan.ALIGN_BASELINE);
                    stringBuilder.append(String.valueOf(faceElem.getIndex()));
                    stringBuilder.setSpan(span, startIndex, startIndex + getNumLength(faceElem.getIndex()), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    is.close();
                } catch (IOException e) {

                }
                break;
            case Text:
                TIMTextElem textElem = (TIMTextElem) elems;
                stringBuilder.append(textElem.getText());
                break;
        }
        return stringBuilder;
    }

    private static int getNumLength(int n) {
        return String.valueOf(n).length();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK && fileUri != null) {
                showImagePreview(fileUri.getPath());
            }
        } else if (requestCode == IMAGE_STORE) {
            if (resultCode == RESULT_OK && data != null) {
                showImagePreview(FileUtil.getFilePath(this, data.getData()));
            }

        } else if (requestCode == FILE_CODE) {
            if (resultCode == RESULT_OK) {
                sendFile(FileUtil.getFilePath(this, data.getData()));
            } else {
                Notification.toast(this, getString(R.string.chat_file_not_exist));
            }
        } else if (requestCode == IMAGE_PREVIEW) {
            if (resultCode == RESULT_OK) {
                boolean isOri = data.getBooleanExtra("isOri", false);
                String path = data.getStringExtra("path");
                File file = new File(path);
                if (file.exists()) {
                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    BitmapFactory.decodeFile(path, options);
                    if (file.length() == 0 && options.outWidth == 0) {
                        Notification.toast(this, getString(R.string.chat_file_not_exist));
                    } else {
                        if (file.length() > 1024 * 1024 * 10) {
                            Notification.toast(this, getString(R.string.chat_file_too_large));
                        } else {
                            Message message = new ImageMessage(path, isOri);
                            presenter.sendMessage(message.getMessage());
                        }
                    }
                } else {
                    Notification.toast(this, getString(R.string.chat_file_not_exist));
                }
            }
        } else if (requestCode == VIDEO_RECORD) {
            /*   // 屏蔽视频消息
            if (resultCode == RESULT_OK) {
                String videoPath = data.getStringExtra("videoPath");
                String coverPath = data.getStringExtra("coverPath");
                long duration = data.getLongExtra("duration", 0);
                Message message = new UGCMessage(videoPath, coverPath, duration);
                presenter.sendMessage(message.getMessage());
            }*/
        }

    }


    private void showImagePreview(String path) {
        if (path == null) return;
        Intent intent = new Intent(this, ImagePreviewActivity.class);
        intent.putExtra("path", path);
        startActivityForResult(intent, IMAGE_PREVIEW);
    }

    private void sendFile(String path) {
        if (path == null) {
            Notification.toast(this, getString(R.string.chat_file_not_exist));
            return;
        }
        File file = new File(path);
        if (file.exists()) {
            if (file.length() > 1024 * 1024 * 10) {
                Notification.toast(this, getString(R.string.chat_file_too_large));
            } else {
                Message message = new FileMessage(path);
                presenter.sendMessage(message.getMessage());
            }
        } else {
            Notification.toast(this, getString(R.string.chat_file_not_exist));
        }

    }

    /**
     * 将标题设置为对象名称
     */
    private Runnable resetTitle = new Runnable() {
        @Override
        public void run() {
            if (titleStr.equals(identify)) {
                titleStr = titleStr.replace("qa", "").replace("prod", "");
            }
            title.setTitleText(titleStr);
        }
    };


    @Override
    public void onBackPressed() {
        if (!input.interceptBackPress()) {
            finish();
        }
    }
}
